package com.example.ec.controller;

import com.example.ec.pojo.Goods;
import com.example.ec.pojo.User;
import com.example.ec.service.GoodsService;
import com.example.ec.service.UserService;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Set;

/**
 * ClassName:UserColltroller
 * Package:com.example.ec.controller
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/4/8-9:56
 * @Version:v1.0
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    private final UserService userService;
    private final GoodsService goodsService;

    public UserController(UserService userService, GoodsService goodsService) {
        this.userService = userService;
        this.goodsService = goodsService;
    }

    @PostMapping("signIn")
    private String signIn(User user) {
        user = userService.queryOne("queryById", user.getId());
        if (user == null) {
            session.setAttribute("error", "请先注册");
            return "redirect:/index.jsp";
        }
        if (user.getId() == 1 && "admin".equals(user.getUsername())) {
            List<User> goods = userService.queryList("queryGoods", new Goods());
            session.setAttribute("goods", goods);
            session.setAttribute("user", user);
            return "redirect:/admin/index.jsp";
        } else {
            List<User> goods = userService.queryList("queryGoods", new Goods());
            session.setAttribute("goods", goods);
            session.setAttribute("user", user);
            return "redirect:/goods.jsp";
        }
    }

    @PostMapping("signUp")
    private String signUp(User user) {
        try {
            User userSql = userService.queryOne("queryByUsername", user);

            if (user.getUsername().equals(userSql.getUsername())) {
                session.setAttribute("a", "该用户名已存在");
                return "redirect:/sign_up.jsp";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        userService.create("create", user);
        session.setAttribute("id", "您的Id是：" + userService.queryOne("queryByUsername", user).getId());
        return "redirect:/index.jsp";
    }

    @GetMapping("signOut")
    private String signOut() {
        session.invalidate();
//
        return "redirect:/index.jsp";
    }

    @GetMapping("signOut2")
    private String signOut2(){
        session.setAttribute("goods",userService.queryList("queryGoods", new Goods()));
        return "redirect:/goods.jsp";
    }

}
